package servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import utils.JDBCUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Method;

public class BaseServlet extends HttpServlet {

    protected static final ObjectMapper objectMapper = new ObjectMapper().registerModule(new JavaTimeModule());

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String operation = req.getParameter("operation");
        System.out.println("本次调用方法：" + operation);
        Method[] methods = this.getClass().getDeclaredMethods();
        for (Method method : methods) {
            if (method.getName().equals(operation)) {
                try {
                    method.invoke(this, req, resp);
                } catch (Exception e) {
                    Throwable rootCause = findRootCause(e);
                    if (rootCause != null) {
                        StringWriter sw = new StringWriter();
                        PrintWriter pw = new PrintWriter(sw);
                        rootCause.printStackTrace(pw);
                        String stackTrace = sw.toString();
//                        这里统一打印异常堆栈信息
                        e.printStackTrace();
                    }
                } finally {
                    JDBCUtils.closeConnection();
                }
            }
        }
    }

    private Throwable findRootCause(Throwable throwable) {
        Throwable rootCause = throwable;
        while (rootCause.getCause() != null) {
            rootCause = rootCause.getCause();
        }
        return rootCause;
    }

    // 响应json
    protected static void sendJsonResponse(HttpServletResponse response, Object responseObject) throws IOException {
        String json = objectMapper.writeValueAsString(responseObject);
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();
        out.print(json);
        out.flush();
    }
}

